package jetbrains.buildServer.cuta.utils;

import jetbrains.buildServer.util.XmlUtil;
import org.jdom.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;




/**
 * @author Leonid Bushuev from JetBrains
 */
public final class DomUtil
{

    public static String getAttrString(@Nullable Element element, @NotNull String attrName, @Nullable String defaultValue)
    {
        if (element == null)
            return defaultValue;
        String attr = element.getAttributeValue(attrName);
        if (attr == null)
            return defaultValue;
        return attr.trim();
    }


    public static String getContent(@Nullable Element element)
    {
        if (element == null)
            return null;

        String output = XmlUtil.to_s(element);
        int p1 = output.indexOf('>');  assert p1 >= 0;
        int p2 = output.lastIndexOf('<');  assert p2 >= 0;

        return p1 < p2
                ? output.substring(p1 + 1, p2).trim()
                : null;
    }


    public static String getNestedContent(@Nullable Element element, @NotNull String nestedElementName, String defaultValue)
    {
        if (element == null)
            return defaultValue;
        Element nestedElement =
                element.getChild(nestedElementName);
        String content = getContent(nestedElement);
        return content != null ? content : defaultValue;
    }

}
